
import { _decorator, Component, resources, SpriteFrame, random } from 'cc';
import DataManager from '../../Runtime/DataManager';
import ResourceManager from '../../Runtime/ResourceManager';
const { ccclass, property } = _decorator;
import { createUINode, randomByRange } from '../Utils';
import { TileManager } from './TileManager';


@ccclass('TileMapManager')
export class TileMapManager extends Component {
  async init() {
    // 从数据中心取到当前地图的数据
    const { mapInfo } = DataManager.Instance
    // 加载资源
    const spriteFrames = await ResourceManager.Instance.loadDir('texture/tile/tile')
    // 初始化方块可走性信息
    DataManager.Instance.tileInfo = []
    // 给每个地图块上色、摆位置
    for(let i = 0; i < mapInfo.length; i++) {
      const column = mapInfo[i]
      DataManager.Instance.tileInfo[i] = []
      for (let j = 0; j < column.length; j++) {
        const item = column[j];
        if (item.src === null || item.type === null) {
          continue
        }

        // 随机改变贴图
        let number = item.src
        if((number === 1 || number === 5 || number === 9) && i % 2 === 0 && j % 2 === 0) {
          number += randomByRange(0, 4)
        }

        // 使用封装 ui
        const node = createUINode()
        const imgSrc = `tile (${number})`
        const spriteFrame = spriteFrames.find(v => v.name === imgSrc) || spriteFrames[0]
        // 使用专门的 TileManager 设置它的位置信息
        const tileManager = node.addComponent(TileManager)
        const type = item.type
        tileManager.init(type,spriteFrame, i, j)
        // 将携带可走性信息的
        DataManager.Instance.tileInfo[i][j] = tileManager
        node.setParent(this.node)
      }
    }
  }


}
